package mz.matafe.bolao

import org.codehaus.groovy.grails.plugins.springsecurity.Secured
import mz.matafe.bolao.exception.*

import grails.converters.JSON
import groovy.xml.MarkupBuilder

@Secured(['ADMINISTRATOR','ROLE_SUPERVISOR','ROLE_USER'])
class BetController extends BolaoController{

    def betService
    
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        def groups = Group.list()
        def matches = Match.list()
        def user = authenticateService.userDomain()
        def bets = Bet.findAllByUser(user)
        [ groups: groups, matches: matches, bets: bets ]
    }

    def create = {
        def match = Match.get(params.id)
        if (!match) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'match.label', default: 'Match'), params.id])}"
            redirect(action: "list")
            return
        }

        def bet = new Bet()
        bet.properties = params
        return [bet: bet, match: match]
    }

    def save = {
        println params
        def user = getUser()
        def bet = new Bet(params)
        if (bet.validate()){
            try{
                bet = betService.doBet(user, bet)
                flash.message = "${message(code: 'default.created.message', args: [message(code: 'bet.label', default: 'Bet'), bet?.match?.team1?.name + ' x ' + bet?.match?.team2?.name])}"
                redirect(action: "list")
            }catch (ServiceException se){
                println 'Ops!!'
                flash.message = message(code:se.messageKey, args:se.args)
            }
        }
        def match = Match.get(params.match.id)
        render(view: "create", model: [bet: bet, match: match])
    }

    def show = {
        def bet = Bet.get(params.id)
        if (!bet) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bet.label', default: 'Bet'), params.id])}"
            redirect(action: "list")
        }
        else {
            [bet: bet]
        }
    }

    def edit = {
        def bet = Bet.get(params.id)
        if (!bet) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bet.label', default: 'Bet'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [bet: bet]
        }
    }

    def update = {
        def bet = Bet.get(params.id)
        if (bet) {
            if (params.version) {
                def version = params.version.toLong()
                if (bet.version > version) {
                    
                    bet.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'bet.label', default: 'Bet')] as Object[], "Another user has updated this Bet while you were editing")
                    render(view: "edit", model: [bet: bet])
                    return
                }
            }
            bet.properties = params
            if (!bet.hasErrors() && bet.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'bet.label', default: 'Bet'), bet?.match?.team1?.name + ' x ' + bet?.match?.team2?.name])}"
                redirect(action: "list")
            }
            else {
                render(view: "edit", model: [bet: bet])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bet.label', default: 'Bet'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def bet = Bet.get(params.id)
        if (bet) {
            try {
                bet.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'bet.label', default: 'Bet'), bet?.match?.team1?.name + ' x ' + bet?.match?.team2?.name])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'bet.label', default: 'Bet'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bet.label', default: 'Bet'), params.id])}"
            redirect(action: "list")
        }
    }

    @Secured(['ROLE_ADMIN','ROLE_SUPERVISOR','ROLE_USER'])
    def ajaxGetBetters = {
        //println "))))))))))))))"
        /*
        def roleUser = [Role.findByCode('ROLE_USER')]
        def criteria = User.createCriteria()
        def users = criteria {
        roles{
        eq('id', roleUser.id)
        }
        }
         */
        /*
        def users = User.list()
        users.each{
        print it
        }
        render users as JSON

         */

        def out = new StringWriter()
        def b = new MarkupBuilder(out)
        b.table(id: 'test', border: 1) {
            tbody {
                tr {
                    td "hello"
                    td(id: 'hello_id', 'hello')
                }
            }
        }
        //render out.toString()
        // render some HTML markup to the body
        def users = User.list()
        render(contentType:"text/html") {
                for(u in users) {
                    a href: u.username, u.firstname
                    br()
                }
        }

    }
}
